package com.study;


import javassist.ClassPool;
import javassist.CtClass;
import javassist.CtMethod;
import javassist.NotFoundException;
import javassist.bytecode.*;
import org.objectweb.asm.*;
import org.springframework.core.DefaultParameterNameDiscoverer;
import org.springframework.core.LocalVariableTableParameterNameDiscoverer;

import java.io.IOException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

/**
 * [java读取方法参数名称，read the names of the parameters of a method \- baowp \- ITeye博客](https://baowp.iteye.com/blog/2196814)
 * [java1\.8中javassist获取接口函数参数名称 \- chy2z的专栏 \- CSDN博客](https://blog.csdn.net/chy2z/article/details/81744808)
 * [Java获取方法参数名的几种方式 · TFdream/blog Wiki](https://github.com/TFdream/blog/wiki/Java%E8%8E%B7%E5%8F%96%E6%96%B9%E6%B3%95%E5%8F%82%E6%95%B0%E5%90%8D%E7%9A%84%E5%87%A0%E7%A7%8D%E6%96%B9%E5%BC%8F)
 */
public class 获取类方法参数名 {
    private static DefaultParameterNameDiscoverer nameDiscoverer =new DefaultParameterNameDiscoverer();

    private static LocalVariableTableParameterNameDiscoverer localVariableTableParameterNameDiscoverer = new LocalVariableTableParameterNameDiscoverer();

    public static void main(String[] args) {
//        Method[] methods = HomeworkDtlDao.class.getDeclaredMethods();
        Method[] methods = Method.class.getDeclaredMethods();

//        System.out.println(localVariableTableParameterNameDiscoverer.getParameterNames(methods[0]));
//        System.out.println(nameDiscoverer.getParameterNames(methods[0]));
//        System.out.println(getMethodParamNamesByAsm(methods[0]));
//        System.out.println(getMethodParamNamesByAssist(methods[0]));
        getMethodParamNamesByAssist(methods[0]);
    }
    public static List<String> getParamterName(Class clazz, String methodName) {
        LocalVariableTableParameterNameDiscoverer u = new LocalVariableTableParameterNameDiscoverer();
        Method[] methods = clazz.getDeclaredMethods();
        for (Method method : methods) {
            if (methodName.equals(method.getName())) {
                //获取到该方法的参数们
                String[] params = u.getParameterNames(method);
                if(params ==null){
                    return new ArrayList<>();
                }
                return Arrays.asList(params);
            }
        }
        return null;
    }

    /** 使用ASM来获取方法的参数名 */
    public static String[] getMethodParamNamesByAsm(final Method method)  {

        final String methodName = method.getName();
        final Class<?>[] methodParameterTypes = method.getParameterTypes();
        final int methodParameterCount = methodParameterTypes.length;
        final String className = method.getDeclaringClass().getName();
        final boolean isStatic = Modifier.isStatic(method.getModifiers());
        final String[] methodParametersNames = new String[methodParameterCount];

        ClassReader cr = null;
        try {
            cr = new ClassReader(className);
        } catch (IOException e) {
            e.printStackTrace();
        }
        ClassWriter cw = new ClassWriter(ClassWriter.COMPUTE_MAXS);
        cr.accept(new ClassAdapter(cw) {
            @Override
            public MethodVisitor visitMethod(int access, String name, String desc, String signature, String[] exceptions) {

                MethodVisitor mv = super.visitMethod(access, name, desc, signature, exceptions);

                final Type[] argTypes = Type.getArgumentTypes(desc);

                //参数类型不一致
                if (!methodName.equals(name) || !matchTypes(argTypes, methodParameterTypes)) {
                    return mv;
                }
                return new MethodAdapter(mv) {
                    @Override
                    public void visitLocalVariable(String name, String desc, String signature, Label start, Label end, int index) {
                        //如果是静态方法，第一个参数就是方法参数，非静态方法，则第一个参数是 this ,然后才是方法的参数
                        int methodParameterIndex = isStatic ? index : index - 1;
                        if (0 <= methodParameterIndex && methodParameterIndex < methodParameterCount) {
                            methodParametersNames[methodParameterIndex] = name;
                        }
                        super.visitLocalVariable(name, desc, signature, start, end, index);
                    }
                };
            }
        }, 0);
        return methodParametersNames;
    }

    /**
     * 比较参数是否一致
     */
    private static boolean matchTypes(Type[] types, Class<?>[] parameterTypes) {
        if (types.length != parameterTypes.length) {
            return false;
        }
        for (int i = 0; i < types.length; i++) {
            if (!Type.getType(parameterTypes[i]).equals(types[i])) {
                return false;
            }
        }
        return true;
    }


    public static String[] getMethodParamNamesByAssist(final Method method) {
        String[] paramNames = null;
        try {
            //获取要操作的类对象
            ClassPool pool = ClassPool.getDefault();
            CtClass ctClass = pool.get(method.getDeclaringClass().getName());
            int count = method.getParameterCount();
            Class<?>[] paramTypes = method.getParameterTypes();
            CtClass[] ctParams = new CtClass[count];
            for (int i = 0; i < count; i++) {
                ctParams[i] = pool.getCtClass(paramTypes[i].getName());
            }

            CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName(), ctParams);
            //得到该方法信息类
            MethodInfo methodInfo = ctMethod.getMethodInfo();

            //获取属性变量相关
            CodeAttribute codeAttribute = methodInfo.getCodeAttribute();

            //获取方法本地变量信息，包括方法声明和方法体内的变量
            //需注意，若方法为非静态方法，则第一个变量名为this
            LocalVariableAttribute attr = (LocalVariableAttribute) codeAttribute.getAttribute(LocalVariableAttribute.tag);
            int pos = Modifier.isStatic(method.getModifiers()) ? 0 : 1;

            paramNames = new String[count];
            for (int i = 0; i < count; i++) {
                paramNames[i] = attr.variableName(i + pos);

            }
        }  catch (NotFoundException e) {
            e.printStackTrace();
        }
        return paramNames;
    }

    public static void getInterfaceParamterNameByAssist(Method method){
        ClassPool pool = ClassPool.getDefault();
        try {
            CtClass ctClass = pool.get(method.getDeclaringClass().getName());
            CtMethod ctMethod = ctClass.getDeclaredMethod(method.getName());
            // 使用javassist的反射方法的参数名
            MethodInfo methodInfo = ctMethod.getMethodInfo();

            MethodParametersAttribute methodParameters= (MethodParametersAttribute)methodInfo.getAttribute("MethodParameters");

            //获取参数的个数
            int count =ctMethod.getParameterTypes().length;

            CtClass[] pCtClass= ctMethod.getParameterTypes();

            for(int i=0;i<count;i++) {
                String str = methodParameters.getConstPool().getUtf8Info(ByteArray.readU16bit(methodParameters.get(), i * 4 + 1));
                System.out.println("参数名称:" + str + ",参数类型" + pCtClass[i].getName());
            }

            System.out.println("");
            System.out.println(method.getName()+"获取结束");
            System.out.println("");

        } catch (NotFoundException e) {
            e.printStackTrace();
        }
    }
}
